// function A() {
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       console.log("A");
//       reject("A rejected");
//       resolve("A resolved");
//     }, 1000);
//   });
// }

// function B() {
//   console.log("B");
// }

// // 0ms后，A就返回了一个Promise对象，此时状态为pending
// // 1000ms后，A的Promise对象状态变为resolved，then中的回调函数执行
// A().then(
//   () => {
//     B();
//   },
//   (err) => {
//     console.log(err);
//   }
// );

class MyPromise {
  constructor(executor) {
    this.status = "pending"; // 状态
    this.value = null; // 成功的结果
    this.reason = null; // 失败的原因
    this.onResolvedCallbacks = []; // 存放then成功的回调函数
    this.onRejectedCallbacks = []; // 存放then失败的回调函数

    const resolve = (value) => {
      if (this.status === "pending") {
        this.value = value;
        this.status = "fulfilled";
        this.onResolvedCallbacks.forEach((fn) => fn(value));
      }
    };
    const reject = (reason) => {
      if (this.status === "pending") {
        this.reason = reason;
        this.status = "rejected";
        this.onRejectedCallbacks.forEach((fn) => fn(reason));
      }
    };
    executor(resolve, reject);
  }
  then(onFulfilled, onRejected) {
    onFulfilled =
      typeof onFulfilled === "function" ? onFulfilled : (value) => value;
    onRejected =
      typeof onRejected === "function"
        ? onRejected
        : (reason) => {
            throw reason;
          };

    // 返回一个新的Promise对象
    let newPromise = new MyPromise((resolve, reject) => {
      if (this.status === "fulfilled") {
        setTimeout(() => {
          try {
            const result = onFulfilled(this.value); // 作为异步任务
            if (result instanceof MyPromise) {
              newPromise = result;
            }
            resolve(result);
          } catch (error) {
            reject(error);
          }
        });
      }
      if (this.status === "rejected") {
        setTimeout(() => {
          try {
            const result = onRejected(this.reason); // 作为异步任务
            if (result instanceof MyPromise) {
              newPromise = result;
            }
            resolve(result);
          } catch (error) {
            reject(error);
          }
        });
      }
      if (this.status === "pending") {
        this.onResolvedCallbacks.push((value) => {
          setTimeout(() => {
            try {
              const result = onFulfilled(value); // 作为异步任务
              if (result instanceof MyPromise) {
                newPromise = result;
              }
              resolve(result);
            } catch (error) {
              reject(error);
            }
          })
        })
        this.onRejectedCallbacks.push((reason) => {
          setTimeout(() => {
            try {
              const result = onRejected(reason); // 作为异步任务
              if (result instanceof MyPromise) {
                newPromise = result;
              }
              resolve(result);
            } catch (error) {
              reject(error);
            }
          })
        })
      }
    });
    return newPromise;
  }
}

let p = new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("ok");
    }, 1000);
//   reject("no");
});
p.then((res) => {
  console.log(res,'then');
})
